package net.wzw.localcache;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;

/**
 * @author wzw
 * @date 2025/5/3
 * @Description
 */
@Slf4j
public class Encache {

    public static void main(String[] args) throws Exception {
        // 声明一个cacheBuilder
        CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
                .withCache("encacheInstance", CacheConfigurationBuilder
                        // 声明一个容量为 20 的堆内缓存
                        .newCacheConfigurationBuilder(String.class,String.class, ResourcePoolsBuilder.heap(20)))
                .build(true);
        // 获取 Cache 实例
        Cache<String,String> myCache =  cacheManager.getCache("encacheInstance", String.class, String.class);

        String orderId = String.valueOf(123456789);
        String orderInfo = myCache.get(orderId);
        if (StringUtils.isBlank(orderInfo)) {
            orderInfo = getInfo(orderId);
            myCache.put(orderId, orderInfo);
        }
        log.info("orderInfo = {}", orderInfo);

        cacheManager.close();
    }

    private static String getInfo(String orderId) {
        String info = "";
        // 先查询redis缓存
        log.info("get data from redis");

        // 当redis缓存不存在查db
        log.info("get data from mysql");
        info = String.format("{orderId=%s}", orderId);
        return info;
    }

}
